import fs from 'fs';
import path from 'path';
import multer from '@koa/multer';
import { ResumeEntity } from '../utils/repository';
import { ResumeService } from './resume.service';

import { Service, Inject } from 'typedi';

const basePath = 'public/upload';

@Service()
export class FileService {
  @Inject()
  resumeService: ResumeService;

  /**
   * 上传文件
   * @param uid
   * @param file
   */
  async uploadFile(uid: string, file: multer.File) {
    try {
      const time = new Date().getTime().toString();
      const suffix = '.' + file.mimetype.split('/')[1];
      const filePath = path.resolve(basePath, time + suffix);
      const resume = new ResumeEntity();
      resume.name = file.originalname.split('.')[0];
      resume.file = `/file/download/${time + suffix}`;
      resume.type = 1;
      resume.uid = uid;
      const index = await this.resumeService.save(resume);
      if (index == 1) {
        fs.writeFileSync(filePath, file.buffer);
        return true;
      }
      return false;
    } catch (error) {
      console.log(error);
      return false;
    }
  }

  /**
   * 下载文件
   * @param filename
   */
  async downloadFile(filename: string) {
    try {
      const filePath = path.resolve(basePath, filename);
      const content = fs.readFileSync(filePath);
      return content;
    } catch (error) {
      console.log(error);
      return false;
    }
  }
}
